import * as c from '@/util/config'
import * as u from '@/util/util.js'
import {router} from "@/router/index.js";

/**
 * 获取菜单动态路由信息
 * @returns {*}
 */
export function getDynamicRoutes() {
    const tree = u.getSession(c.sessionKey.SYS_MENU_TREE) || []
    return buildRoutes(tree)
}


/**
 * 构建路由信息
 * @param tree
 * @returns {*[]}
 */
export function buildRoutes(tree = []) {
    const modules = import.meta.glob('@/view/**/*.vue')
    const routes = []
    for (const item of tree) {
        if (item.children?.length) {
            routes.push(...buildRoutes(item.children))
        }
        if (item.type === '1') {
            const path = item.path
            const name = item.name
            const keepAlive = item.cache === 'Y'
            const filePath = `/src/view${path}.vue`
            const component = modules[filePath]
            if (!component) {
                console.warn(`动态路由组件未找到: ${filePath}`)
                continue
            }
            routes.push({
                path,
                name,
                meta: { title: name, keepAlive },
                component,
            })
        }
    }
    return routes
}


/**
 * 创建动态路由
 */
export function createDynamicRoute(){
    getDynamicRoutes().forEach(route => {
        router.addRoute('admin', route)
    })
    // 添加404路由
    router.addRoute({
        path: '/:pathMatch(.*)*',
        name: 'not-found',
        meta: { title: '404' },
        component: () => import('@/view/404.vue')
    })
}